var Rose = {};

Rose.Sandbox = $('<div style="left:-10000px;top:-10000px;position: absolute;" />');
Rose.Container = $('<div/>');

$(document).ready(function() {
	$(document.body).append(Rose.Sandbox);
	$(document.body).append(Rose.Container);
});

Rose.Config = {
	debug: true
};

Rose.Cache = {};

var p = function() {
	if (console && Rose.Config.debug) console.debug.apply(console, arguments);
};

Rose.preLoad = function(url) {
	$.ajax({
		url: url,
		success: function(data) {
			Rose.Cache[url] = data;
			Rose.Container.trigger('data:' + url, [data]);
		}
	});
};

Rose.loadData = function(url, callback, context) {
	if (! context) context = this;
	if (url in Rose.Cache) {
		callback.call(context, url);
	}
	else {
		$.ajax({
			url: url,
			sucess: function(data) {
				callback.call(context, url);
			}
		});
	}
};

Rose.loadPage = function(url) {
	var _loadPage = function(data) {
		Rose.Container.empty().html(data);
	};
	if (url in Rose.Cache) {
		_loadPage(Rose.Cache[url]);
		delete Rose.Cache[url];
	}
	else {
		$.ajax({
			url: url,
			success: _loadPage
		});
	}
};

Rose.Widget = Class.create({
	initialize: function(options, $container) {
		this.options = this._initOptions(options);
		this.$container = $container;
		this.render();
	},
	
	render: function() {
		this._render();
		if (this.$container) this.$container.append(this.$dom);
		else Rose.Sandbox.append(this.$dom);
	},
	
	_render: function() {
		this.$dom = $('<div/>').addClass('rose-widget');
	},
	
	_initOptions: function(options) {
		var data = $H(options);
		var result = $H({});
		data.each(function(pair) {
			var key = pair.key;
			result.set(key, pair.value);
		});
		this._options = result;
	},
	
	option: function(key, value) {
		if (arguments.length == 1) {
			if (Object.isArray(key)) {
				return this._options.get(key[0]) || key[1] || null;
			}
			return this._options.get(key) || null;
		}
		this._options.set(key, value);
	},
	
	dom: function() {
		return this.$dom;
	},
	
	append: function(widget) {
		if (widget.dom) this.$dom.append(widget.dom());
		else this.$dom.append(widget);
	}
	
});

Rose.HtmlWidget = Class.create(Rose.Widget, {
	initialize: function($super, $dom, options, $container) {
		this.$dom = $dom;
		if (!$container && $dom && $dom.parent) {
			$container = $dom.parent();
		}
		$super(options, $container);
	},
	
	_render: function() {
		var self = this;
		if (Object.isString(this.$dom)) {
			this.$dom = $(this.$dom);
		}
		else if (! this.$dom) {
			this.$dom = $(this._html.substring(lines.indexOf("/*\r\n") + 4, lines.lastIndexOf("*/")));
		}
		$("[rose_id]", this.$dom).each(function(index, d) {
			var name = $(d).attr('rose_id');
			if (name.charAt(0) == '$') self[name] = $(d);
			if (self.option(name)) $(d).text(self.option(name));
		});
	},
	
	//input your widget html as comment in _html
	_html: function() {/*
		<div/>
	*/}
});

Rose.WordContainer = Class.create(Rose.Widget, {
	colors: ['rgb(102, 255, 104)', 'rgb(255, 204, 102)', 'rgb(204, 102, 255)', 
	         'rgb(102, 255, 255)', 'rgb(255, 128, 0)', 'rgb(128, 255, 0)',
	         'rgb(128, 0, 255)', 'rgb(51, 51, 51)', 'rgb(0, 64, 128)'],
	         
	positions: [[0.5, 0.5], [0.375, 0.33], [0.75, 0.5], [0.25, 0.5], [0.625, 0.33],
	            [0.375, 0.66], [0.625, 0.66], [0.125, 0.16], [0.125, 0.83], [0.875, 0.16]
	],
	
	_render: function($super) {
		$super();
		this.boxSize = [$(window).width(), $(window).height()];
		this.$dom.addClass("rose-word-container").css('height', this.boxSize[1] + 'px').css('width', this.boxSize[0] + 'px');
		var self = this;
		$.ajax({
			url: '/fc/words',
			success: function(data) {
				data = $.parseJSON(data);
				$(data).each(function(index, word) { self.addWord(index, word); } );
			}
		});
	},
	
	getPosition: function(index) {
		return this.positions[index % this.positions.length];
	},

	addWord: function(index, word) {
		var oriPosition = [this.boxSize[0] / 2, this.boxSize[1] / 2];
		var link = '/fc/word/' + word.pk;
		var $linkNode = $('<a/>').attr('href', '#').addClass("rose-word").text(word.fields.name).css('color', this.colors[Math.round(Math.random() * this.colors.length)]).click(function(){
			$.mobile.changePage(link);
		});
		Rose.Sandbox.append($linkNode);
		var size = [$linkNode.width(), $linkNode.height()];
		$linkNode.css('font-size', 30 - index).css('top', oriPosition[1] - size[1] / 2 + 'px')
			.css('left', oriPosition[0] - size[0] / 2 + 'px');
		var position = this.getPosition(index);
		position = [position[0] * this.boxSize[0], position[1] * this.boxSize[1]];
		this.$dom.append($linkNode);
		$linkNode.animate({
			left: position[0] - size[0] / 2 + (Math.random() * 30) + 15, top: position[1] - size[1] / 2 + (Math.random() * 30) + 15
		}, 1000);
	}
});

Rose.Comment_Dialog = Class.create(Rose.HtmlWidget, {
	initialize: function($super, $dom, options, $container) {
		$super($dom, options, $container);
		this.$dom = $dom;
		this.id = $dom.attr('wordid');
		this.content = $('.content',this.$dom).text();
		this._init();
	},
	
	_init: function() {
		var self = this;
	},
	
	_submit: function(type) {
		if(!this.content.empty())
		{
			$.ajax({
				type: 'POST',
				url: '/fc/word/vote/' + this.id + "?type=" + type
			});
		}
		else
		{
			$.ajax({
				url: '/fc/word/vote/' + this.id + "?type=" + type
			});
		}
	},
});

Rose.Word = Class.create(Rose.HtmlWidget, {
	initialize: function($super, $dom, options, $container) {
		$super($dom, options, $container);
		this.id = $dom.attr('wordid');
		this.$dom = $dom;
		this._init();
		this.comment_dialog = new Rose.Comment_Dialog($('.comment-dialog'), this.$dom);
	},
	
	_init: function() {
		var self = this;
		$('.vote', this.$dom).click(function() {
			self._click($(this).attr('type'));
		});
	},
	
	_click: function(type) {
		if(type == 'nb' || type == 'sb')
		{
			this.comment_dialog.$dom.show(500);
		}
		else
		{
			///TODO: add page jump to search page
		}
	}
});

Rose.CommentContainer = Class.create(Rose.HtmlWidget, {
	initialize: function($super, $dom, options, $container) {
		$super($dom, options, container);
		this.start = 0;
		this.pageSize = 10;
		this.isCompleted = false;
		this.urlBase = "/fc/word/" + this.option('wordId') + "/comment/load?";
		var self = this;
		this.$more.click(function(){
			if (! self.isCompleted) Rose.loadData(self.dataUrl(), self.loadData, self);
			else {
				//alert message for no more comment
			}
		});
	},
	
	_html: function() {/*
		<div>
			<div rose_id="$commentContainer"></div>
			<div rose_id="$more">More</div>
		</div>
	*/},
	
	_render: function($super) {
		$super();
		Rose.loadData(this.dataUrl(), this.loadData, this);
	},
	
	dataUrl: function() {
		return this.urlBase + "start=" + this.start +"&count=" + this.pageSize;
	},
	
	loadData: function(data) {
		data = $.parseJSON(data);
		if (data && data.length) {
			var self = this;
			$(data).each(function(index, c) {
				new Rose.Comment({
					username: c.fields.user,
					voteAttribute: c.fields.vote,
					content: c.fields.content
				}, self.$commentContainer);
			});
			this.start += data.length;
			this.preLoad(this.DataUrl());
		}
		else {
			this.isCompleted = true;
		}
	}
});

Rose.Comment = Class.create(Rose.HtmlWidget, {
	_html: function() {/*
		<div class="comment">
			<div>
				<div class="comment-username" rose_id="$username"></div>
				<div class="comment-vote" rose_id="$vote"></div>
			</div>
			<div rose_id="content"></div>
		</div>
	*/},
	
	_render: function($super) {
		$super();
		this.$vote.addClass(this.option('voteAttribute'));
	}
});
